package com.polaris.live.utils

import com.google.common.cache.CacheBuilder
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.im.db.database.AppDatabase
import com.polaris.live.im.manager.ImSessionManager
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.back_resp.toUserBasicVo
import com.polaris.live.resp.event.UserUpdateEvent
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit


/**
 * OtherUserCacheUtils 缓存获取过其他人数据
 * @author Created by 天晴 on 2024/1/5 10:09
 * @since 1.0.0
 **/
object OtherUserCacheUtils {
    // 创建一个缓存，设置最大缓存条目为20，过期时间为5分钟
    val cache = CacheBuilder.newBuilder()
        .maximumSize(20)
        .expireAfterWrite(5, TimeUnit.MINUTES)
        .build<Long, InfoOtherResp>()

    fun addUser(infoOtherResp: InfoOtherResp, updateDb: Boolean = false) {
        cache.put(infoOtherResp.userId, infoOtherResp)
        if (updateDb) {
            updateSessionByUserId(infoOtherResp)
        }
    }

    fun removeUser(userId: Long) {
        cache.invalidate(userId)
    }

    operator fun get(userId: Long): InfoOtherResp? {
        return cache.getIfPresent(userId)
    }

    fun clear() {
        cache.invalidateAll()
    }

    /**
     * 更新数据库
     */
    private fun updateSessionByUserId(infoOtherResp: InfoOtherResp) {
        val userJson = JsonUtils.toJson(infoOtherResp.toUserBasicVo())
        ImSessionManager.launchSession {
            AppDatabase.instance.sessionListDao()
                .updateSessionUserByOtherId(UserManager.getUserId(), infoOtherResp.userId, userJson)
            EventBus.getDefault().post(UserUpdateEvent(infoOtherResp.userId))
        }

    }
}